package com.fcy.musicplayer

import android.animation.ObjectAnimator
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.animation.LinearInterpolator
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import com.fcy.musicplayer.base.BaseActivity
import com.fcy.musicplayer.databinding.ActivityPlayMusicBinding
import com.fcy.musicplayer.db.entity.Music
import com.fcy.musicplayer.helps.MediaPlayerHelp
import com.fcy.musicplayer.repository.LocalHelper
import com.fcy.musicplayer.util.BarUtils
import com.fcy.musicplayer.util.LoggerUtil

class PlayMusicActivity : BaseActivity() {
    private lateinit var mediaPlayerHelp: MediaPlayerHelp
    private var id: String? = null
    private var info: Music? = null
    private lateinit var binding: ActivityPlayMusicBinding
    private val animator = MyAnimator()
    override fun onCreate(savedInstanceState: Bundle?) {
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        BarUtils.setStatusBarLightMode(this, true)
        super.onCreate(savedInstanceState)
        playMusic(info)
        binding = DataBindingUtil.setContentView<ActivityPlayMusicBinding?>(
            this,
            R.layout.activity_play_music
        ).apply {
            musicHelp = mediaPlayerHelp
            civAlbum.setOnClickListener { onAlbumClick() }
            mrInner.apply {
                preCallback = {
                    val idd = MediaPlayerHelp.instance.preMusic()
                    if (idd == null) {
                        Toast.makeText(this@PlayMusicActivity, "这是您听的第一首歌哦", Toast.LENGTH_SHORT)
                            .show()
                    } else {
                        this@PlayMusicActivity.id = idd
                        val intent = Intent(this@PlayMusicActivity, PlayMusicActivity::class.java)
                        startActivity(intent)
                    }
                }
                nextCallback = {
                    this@PlayMusicActivity.id = MediaPlayerHelp.instance.nextMusic()
                    val intent = Intent(this@PlayMusicActivity, PlayMusicActivity::class.java)
                    startActivity(intent)
                }
                pauseCallback = {
                    onAlbumClick()
                }
            }
        }
        onContentInit()
        lifecycle.addObserver(animator)
    }

    /**
     * 光盘点击事件
     */
    fun onAlbumClick() {
        if (mediaPlayerHelp.isPlaying.value == true) {
            mediaPlayerHelp.pause()
        } else mediaPlayerHelp.continuePlay()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        /**
         * 先更新音乐信息 然后刷新界面
         */
        info =
            LocalHelper.instance.loadMusicById(id ?: "") ?: MediaPlayerHelp.instance.liveMusic.value
        mediaPlayerHelp.setMusic(info, this)
    }

    /**
     * 界面相关初始化
     *  每次进入新界面都应该调用此方法刷新界面
     */
    private fun onContentInit() {
        binding.mrInner.setValueInner(this)
    }

    private var detector: GestureDetector? = null
    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (detector == null)
            detector = GestureDetector(this, MyGestureDetector())
        detector?.onTouchEvent(ev)
        return super.dispatchTouchEvent(ev)
    }

    override fun initArgs() {
        super.initArgs()
        intent.extras?.apply {
            id = getString("id")
            LoggerUtil.d("====$id")
        }
        info =
            LocalHelper.instance.loadMusicById(id ?: "") ?: MediaPlayerHelp.instance.liveMusic.value
        LoggerUtil.d("$info $id")
    }

    private fun playMusic(music: Music?) {
        mediaPlayerHelp = MediaPlayerHelp.instance.apply {
            setMusic(music, this@PlayMusicActivity)
        }
    }


    inner class MyGestureDetector : GestureDetector.SimpleOnGestureListener() {
        override fun onScroll(
            e1: MotionEvent?,
            e2: MotionEvent?,
            distanceX: Float,
            distanceY: Float
        ): Boolean {
            LoggerUtil.d(distanceY)
            if (distanceY < -15) {
                onBackPressed()
            }
            return super.onScroll(e1, e2, distanceX, distanceY)
        }

    }

    inner class MyAnimator : LifecycleObserver {
        private lateinit var animator: ObjectAnimator

        fun changeState() {
            if (animator.isPaused) {
                animator.resume()
            } else animator.start()
        }

        /**
         * 暂停动画旋转
         */
        @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
        fun onActivityPause() {
            animator.pause()
            LoggerUtil.d("onPause")
        }

        /**
         * 继续动画旋转
         */
        @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
        fun onActivityResume() {
            if (mediaPlayerHelp.isPlaying.value == true) {
                if (!animator.isStarted) {
                    animator.start()
                } else
                    animator.resume()
            } else {
                animator.pause()
            }
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
        fun onActivityCreate() {
            animator = ObjectAnimator.ofFloat(binding.civAlbum, "rotation", 0F, 360F).apply {
                duration = 20000
                repeatCount = -1
                interpolator = LinearInterpolator()
            }
            MediaPlayerHelp.instance.isPlaying.observe(this@PlayMusicActivity) { it ->
                if (it) {
                    if (!animator.isStarted) {
                        animator.start()
                    } else
                        animator.resume()
                } else {
                    animator.pause()
                }
            }
        }
    }
}